package com.axjc.gqzr.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.axjc.gqzr.domain.Gqzr;
import com.axjc.gqzr.listener.MultipleSheetsData;
import com.axjc.gqzr.listener.MultipleSheetsListener;
import com.axjc.gqzr.mapper.GqzrMapper;
import com.axjc.gqzr.service.IFilesService;
import com.axjc.gqzr.util.ApplicationContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.NotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 文件表 服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FilesServiceImpl implements IFilesService {
    private final GqzrMapper gqzrMapper;

    private static final Logger logger = LoggerFactory.getLogger(FilesServiceImpl.class);

    @SneakyThrows
    @Override
    public ResponseEntity<org.springframework.core.io.Resource> download(long id) {
        File file = ResourceUtils.getFile("classpath:cd/股权变更税务申报表.xlsx");

        Gqzr fillData = gqzrMapper.selectById(id);
        String templateFileName = file.getPath();
        // 这里 会填充到第一个sheet， 然后文件流会自动关闭
        File tempFile = File.createTempFile("temp", ".xlsx");
        String tempFilePath = tempFile.getPath();
        MultipleSheetsListener multipleSheetsListener = new MultipleSheetsListener();
        try (ExcelReader excelReader = EasyExcel.read(file, MultipleSheetsData.class, multipleSheetsListener).excelType(ExcelTypeEnum.XLSX).build()) {
            List<ReadSheet> sheets = excelReader.excelExecutor().sheetList();
            ExcelWriter excelWriter = EasyExcel.write(tempFilePath).withTemplate(templateFileName).build();
            for (ReadSheet sheet : sheets) {
                String sheetName = sheet.getSheetName();
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetName).build();
                FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
                excelWriter.fill(fillData, fillConfig, writeSheet);
            }
            excelWriter.finish();
        }


        File file1 = ResourceUtils.getFile(tempFilePath);
        org.springframework.core.io.Resource resource = loadFileAsResource(file1.getPath());
        // Try to determine file's content type
        String contentType = null;
        HttpServletRequest request = ApplicationContextUtil.getRequest();
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if (contentType == null) {
            contentType = "application/octet-stream";
        }

        ResponseEntity<Resource> body = ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
        return  body;
    }

    /**
     * 加载文件作为资源
     *
     * @param fileName 文件名称
     * @return {@link org.springframework.core.io.Resource}
     */
    @SneakyThrows
    public org.springframework.core.io.Resource loadFileAsResource(String fileName) {
        FileSystemResource fileSystemResource = new FileSystemResource(fileName);
        if (fileSystemResource.exists()) {
            return fileSystemResource;
        } else {
            throw new NotFoundException("File not found " + fileName);
        }
    }
}
